<template>
	<div class="chat">
		<!-- <image style="width: 45rpx;position: absolute;right: 20rpx; top: -65rpx;z-index: 999999;"
            src="https://xbb.fuliaoxx.com/img/images/seting.png" mode="widthFix" @click="toSeting"></image> -->

		<div :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
			<div v-if="!currentConversationID" :class="['TUI-chat-default', !isPC && 'TUI-chat-h5-default']">
				<slot></slot>
			</div>
			<div v-if="currentConversationID" :class="['TUI-chat', !isPC && 'TUI-chat-h5']">
				<ChatHeader :class="[
            'TUI-chat-header',
            !isPC && 'TUI-chat-H5-header',
            isUniFrameWork && 'TUI-chat-uniapp-header',
          ]" @closeChat="closeChat"></ChatHeader>
				<MessageList :isChat="isChat" :class="[
            'TUI-chat-message-list',
            !isPC && 'TUI-chat-h5-message-list',
          ]" :isGroup="isGroup" :groupID="groupID" @handleEditor="handleEditor">
				</MessageList>
				<!-- <chatGift /> -->

				<MessageInputToolbar v-show="isToolbarShow" :class="[
            'TUI-chat-message-input-toolbar',
            !isPC && 'TUI-chat-h5-message-input-toolbar', 
          ]" @insertEmoji="insertEmoji"></MessageInputToolbar>
				<MessageInput :isChat="isChat" :class="[
            'TUI-chat-message-input',
            !isPC && 'TUI-chat-h5-message-input',
            isUniFrameWork && 'TUI-chat-uni-message-input',
            isWeChat && 'TUI-chat-wx-message-input',
          ]" :isMuted="false" :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')"
					:placeholder="TUITranslateService.t('想和TA说点什么')" ref="messageInputRef"
					@handleToolbarListShow="handleToolbarListShow"></MessageInput>
			</div>
			<!-- 群组管理 -->
			<div class="group-profile" v-if="isUniFrameWork && isGroup && groupManageExt" @click="handleGroup">
				{{ groupManageExt.text }}
				<!-- 更多 -->
			</div>
		</div>
		<u-modal :show="show" title="提示" :content="content" @confirm="confirm" confirmText="返回"></u-modal>
	</div>
</template>
<script lang="ts" setup>
	// import user from '@/api/_user.js'
	// import { chatId } from '@/api/config.js'
	import {
		TUIChatKit
	} from "@/TUIKit";
	import TUIChatEngine, {
		TUIGlobal,
		TUITranslateService,
		TUIConversationService,
		TUIStore,
		StoreName,
		IMessageModel,
		IConversationModel,
	} from "@tencentcloud/chat-uikit-engine";
	import store from '@/store'
	import { ref, onUnmounted, computed, watch, nextTick } from "../../adapter-vue";
	import ChatHeader from "./chat-header/index.vue";
	import MessageList from "./message-list/index.vue";
	import MessageInput from "./message-input/index.vue";
	import MessageInputToolbar from "./message-input-toolbar/index.vue";
	import TUICore, { TUIConstants, ExtensionInfo } from "@tencentcloud/tui-core";
	import { isUniFrameWork } from "../../utils/is-uni";
	import { onNavigationBarButtonTap, onShow, onLoad, onReady } from '@dcloudio/uni-app'
	// import chatGift from '@/components/chatgift.vue'
	const emits = defineEmits(["closeChat"]);
	const isPC = ref(TUIGlobal.getPlatform() === "pc");
	const isWeChat = ref(TUIGlobal.getPlatform() === "wechat");
	const isToolbarShow = ref<boolean>(!isUniFrameWork);
	const messageInputRef = ref();
	const currentConversationID = ref();
	const chongzhi = ref(false);
	// 是否显示群组管理
	const isGroup = ref(false);
	const groupID = ref("");
	const groupManageExt = ref<typeof ExtensionInfo>(undefined);
	const sideID = ref('')
	const content = ref('')
	const isChat = ref(false)
	const show = ref(false)
	let timer = null;
	TUIStore.watch(StoreName.CONV, {
		currentConversationID: (id : string) => {
			currentConversationID.value = id;
		},
		currentConversation: (conversation : typeof IConversationModel) => {
			isGroup.value = conversation?.type === TUIChatEngine.TYPES.CONV_GROUP;
			if (isUniFrameWork && isGroup.value && groupID.value !== conversation?.groupProfile?.groupID) {
				const extList = TUICore.getExtensionList(
					TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID,
					{ filterManageGroup: isGroup.value }
				);
				groupManageExt.value = extList[0];
			}
			groupID.value = conversation?.groupProfile?.groupID;
		},
	});

	onUnmounted(() => {
		reset();
	});

	// 清空当前 conversationID
	const reset = () => {
		TUIConversationService.switchConversation();
	};
	onLoad((opt : any) => {
		// console.log('TUIChat opt',opt, chatId)
		// isChat.value = chatId !== opt.sideID
		sideID.value = opt.sideID;

	})

	const closeChat = (conversationID : string) => {
		emits("closeChat", conversationID);
		reset();
	};

	const insertEmoji = (emojiObj : object) => {
		messageInputRef?.value?.insertEmoji(emojiObj);
	};
	const toSeting = () => {
		uni.navigateTo({
			url: '/pages/user/set?id=' + currentConversationID.value.replace('C2C', '') + '&from=chat'
		})
	}
	const confirm = () => {
		uni.navigateBack()
	}
	onNavigationBarButtonTap(() => {
		toSeting()
	})
	const handleToolbarListShow = (show ?: boolean) => {
		if (isUniFrameWork) {
			isToolbarShow.value = show ?? !isToolbarShow.value;
		} else {
			isToolbarShow.value = true;
		}
	};

	const handleEditor = (message : typeof IMessageModel, type : string) => {
		if (!message || !type) return;
		switch (type) {
			case "reference":
				// todo
				break;
			case "reply":
				// todo
				break;
			case "reedit":
				if (message?.payload?.text) {
					messageInputRef?.value?.reEdit(message?.payload?.text);
				}
				break;
			default:
				break;
		}
	};

	const handleGroup = () => {
		groupManageExt.value.listener.onClicked({ groupID: groupID.value });
	};
	const fto = () => {
		uni.navigateTo({
			url: '/pages/my/wallet'
		})
	};
	// const RemarkValue = computed(() => {
	// 	return store.state.user.updateRemarkValue
	// })
	// const backRemark = ref(RemarkValue.value + '')

	const getFlag = (val) => {
		var now = new Date();

		// 定义一个待比较的时间
		var myDate = new Date(val);

		// 判断待比较的时间是否在当前时间之前
		if (myDate < now) {
			return false
		} else {
			return true
		}
	}
	onShow(() => {
		// if (backRemark.value != RemarkValue.value) {
		// 	uni.setNavigationBarTitle({
		// 		title: RemarkValue.value
		// 	})
		// }
		// chongzhi.value = false
		// backRemark.value = RemarkValue.value + '';
		// user.userStatus({ id: store.state.user.userInfo.id }).then(res => {
		// 	if (res.data.data.bantime) {
		// 		if (getFlag(res.data.data.bantime)) {
		// 			content.value = '你当前处于禁言状态，禁言时间到:' + res.data.data.bantime;
		// 			uni.hideKeyboard()
		// 			show.value = true;
		// 			return
		// 		}
		// 	}
		// 	user.userStatus({ id: sideID.value }).then(res1 => {
		// 		if (res1.data.data && res1.data.data.status != 'normal') {
		// 			content.value = '当前聊天对象账号被封禁,无法发送信息';
		// 			uni.hideKeyboard()
		// 			show.value = true;
		// 			return
		// 		}
		// 		if (res1.data.data && getFlag(res1.data.data.bantime)) {
		// 			content.value = '对方当前处于禁言状态，禁言时间到:' + res1.data.data.bantime;
		// 			uni.hideKeyboard()
		// 			show.value = true;
		// 			return
		// 		}
		// 		timer = setInterval(() => {
		// 			user.userStatus({ id: store.state.user.userInfo.id }).then(res2 => {
		// 				if (res2.data.data.bantime) {
		// 					if (getFlag(res2.data.data.bantime)) {
		// 						content.value = '你当前处于禁言状态，禁言时间到:' + res2.data.data.bantime;
		// 						uni.hideKeyboard()
		// 						show.value = true;
		// 						clearInterval(timer)
		// 						timer = null;
		// 						return
		// 					}
		// 				}
		// 				user.userStatus({ id: sideID.value }).then(res3 => {
		// 					if (res3.data.data && res3.data.data.status != 'normal') {
		// 						content.value = '当前聊天对象账号被封禁,无法发送信息';
		// 						uni.hideKeyboard()
		// 						show.value = true;
		// 						timer && clearInterval(timer)
		// 						timer = null;
		// 					}
		// 					if (res3.data.data && getFlag(res3.data.data.bantime)) {
		// 						content.value = '对方当前处于禁言状态，禁言时间到:' + res3.data.data.bantime;
		// 						uni.hideKeyboard()
		// 						show.value = true;
		// 						timer && clearInterval(timer)
		// 						timer = null;
		// 					}
		// 				})
		// 			})
		// 		}, 2000)
		// 	})
		// })
	})
	nextTick(() => {
		TUIChatKit.chat && TUIChatKit.chat.getFriendProfile({
			userIDList: [sideID.value]
		}).then((res : any) => {
			console.log('TUIChat res', res)
		})
	})
</script>
<style scoped lang="scss" src="./style/index.scss"></style>
<style>
	.arrearage-bg {
		position: fixed;
		top: 0px;
		display: flex;
		left: 0px;
		align-items: center;
		justify-content: center;
		z-index: 999999;

		background: rgba(0, 0, 0, .6);

		.arrearage {
			width: 600rpx;
		}
	} 
</style>